import { uploadApi } from './api';
import { FileInfo } from './fileListener';

export interface UploadTask {
  id: string;
  fileInfo: FileInfo;
  status: 'pending' | 'uploading' | 'completed' | 'failed';
  progress: number;
  error?: string;
  response?: any;
  startTime?: number;
  endTime?: number;
}

export interface UploadManagerOptions {
  apiKey: string;
  serverConfig?: { host: string; port: number };
  maxConcurrentUploads?: number;
  onTaskStart?: (task: UploadTask) => void;
  onTaskProgress?: (task: UploadTask) => void;
  onTaskComplete?: (task: UploadTask) => void;
  onTaskError?: (task: UploadTask) => void;
}

export class UploadManager {
  private apiKey: string;
  private serverConfig?: { host: string; port: number };
  private maxConcurrentUploads: number;
  private tasks: Map<string, UploadTask> = new Map();
  private uploadingTasks: Set<string> = new Set();
  private onTaskStart?: (task: UploadTask) => void;
  private onTaskProgress?: (task: UploadTask) => void;
  private onTaskComplete?: (task: UploadTask) => void;
  private onTaskError?: (task: UploadTask) => void;

  constructor(options: UploadManagerOptions) {
    this.apiKey = options.apiKey;
    this.serverConfig = options.serverConfig;
    this.maxConcurrentUploads = options.maxConcurrentUploads || 3;
    this.onTaskStart = options.onTaskStart;
    this.onTaskProgress = options.onTaskProgress;
    this.onTaskComplete = options.onTaskComplete;
    this.onTaskError = options.onTaskError;
  }

  // 添加上传任务
  addUploadTask(fileInfo: FileInfo): string {
    const taskId = this.generateTaskId();
    const task: UploadTask = {
      id: taskId,
      fileInfo,
      status: 'pending',
      progress: 0
    };

    this.tasks.set(taskId, task);
    console.log(`📤 添加上传任务: ${fileInfo.name} (ID: ${taskId})`);
    
    // 尝试立即开始上传
    this.processQueue();
    
    return taskId;
  }

  // 获取任务状态
  getTask(taskId: string): UploadTask | undefined {
    return this.tasks.get(taskId);
  }

  // 获取所有任务
  getAllTasks(): UploadTask[] {
    return Array.from(this.tasks.values());
  }

  // 获取待处理任务
  getPendingTasks(): UploadTask[] {
    return this.getAllTasks().filter(task => task.status === 'pending');
  }

  // 获取正在上传的任务
  getUploadingTasks(): UploadTask[] {
    return this.getAllTasks().filter(task => task.status === 'uploading');
  }

  // 处理上传队列
  private async processQueue(): Promise<void> {
    // 检查是否有空闲的上传槽位
    if (this.uploadingTasks.size >= this.maxConcurrentUploads) {
      return;
    }

    // 获取待处理的任务
    const pendingTasks = this.getPendingTasks();
    if (pendingTasks.length === 0) {
      return;
    }

    // 获取下一个要上传的任务
    const nextTask = pendingTasks[0];
    await this.startUpload(nextTask);
  }

  // 开始上传任务
  private async startUpload(task: UploadTask): Promise<void> {
    task.status = 'uploading';
    task.startTime = Date.now();
    task.progress = 0;
    this.uploadingTasks.add(task.id);
    
    this.onTaskStart?.(task);
    console.log(`🚀 开始上传: ${task.fileInfo.name}`);

    try {
      // 读取文件内容
      const fileContent = await this.readFileContent(task.fileInfo.path);
      
      // 创建 File 对象
      const file = new File([fileContent], task.fileInfo.name, {
        type: this.getMimeType(task.fileInfo.name)
      });

      // 执行上传，带进度回调
      const response = await uploadApi.upload(file, this.apiKey, this.serverConfig, (progress: number) => {
        // 更新任务进度
        task.progress = progress;
        this.onTaskProgress?.(task);
        console.log(`📊 上传进度: ${task.fileInfo.name} - ${progress}%`);
      });

      // 检查响应：如果成功或者是文件重复，都视为上传成功
      if (response.success || response.duplicate) {
        // 更新任务状态
        task.status = 'completed';
        task.progress = 100;
        task.response = response;
        task.endTime = Date.now();

        this.onTaskComplete?.(task);
        console.log(`✅ 上传完成: ${task.fileInfo.name} (${this.getUploadDuration(task)}ms)${response.duplicate ? ' (文件已存在)' : ''}`);
      } else {
        // 服务器返回了success: false且不是重复文件的情况
        throw new Error(response.message || '上传失败');
      }

    } catch (error) {
      // 处理上传失败
      task.status = 'failed';
      task.error = error instanceof Error ? error.message : String(error);
      task.endTime = Date.now();
      
      this.onTaskError?.(task);
      console.error(`❌ 上传失败: ${task.fileInfo.name}`, error);
    } finally {
      // 从上传中移除
      this.uploadingTasks.delete(task.id);
      
      // 处理下一个任务
      this.processQueue();
    }
  }

  // 读取文件内容
  private async readFileContent(filePath: string): Promise<ArrayBuffer> {
    if (!window.electronAPI) {
      throw new Error('electronAPI 不可用');
    }
    
    try {
      return await window.electronAPI.readFileAsArrayBuffer(filePath);
    } catch (error) {
      // 提供更详细的错误信息
      if (error instanceof Error) {
        if (error.message.includes('EISDIR')) {
          throw new Error(`路径是一个目录，不是文件: ${filePath}`);
        } else if (error.message.includes('EPERM')) {
          throw new Error(`没有权限读取文件: ${filePath}`);
        } else if (error.message.includes('ENOENT')) {
          throw new Error(`文件不存在: ${filePath}`);
        }
      }
      throw error;
    }
  }

  // 获取MIME类型
  private getMimeType(fileName: string): string {
    const extension = fileName.toLowerCase().split('.').pop();
    const mimeTypes: Record<string, string> = {
      'jpg': 'image/jpeg',
      'jpeg': 'image/jpeg',
      'png': 'image/png',
      'gif': 'image/gif',
      'bmp': 'image/bmp',
      'webp': 'image/webp',
      'tiff': 'image/tiff',
      'tif': 'image/tiff',
      // RAW格式
      'arw': 'image/x-sony-arw',
      'cr2': 'image/x-canon-cr2',
      'cr3': 'image/x-canon-cr3',
      'nef': 'image/x-nikon-nef',
      'orf': 'image/x-olympus-orf',
      'rw2': 'image/x-panasonic-rw2',
      'pef': 'image/x-pentax-pef',
      'srw': 'image/x-samsung-srw',
      'dng': 'image/x-adobe-dng',
      'raf': 'image/x-fuji-raf',
      '3fr': 'image/x-hasselblad-3fr',
      'kdc': 'image/x-kodak-kdc',
      'mos': 'image/x-leaf-mos',
      'mrw': 'image/x-minolta-mrw',
      'nrw': 'image/x-nikon-nrw',
      'gpr': 'image/x-gopro-gpr'
    };
    
    return mimeTypes[extension || ''] || 'application/octet-stream';
  }

  // 生成任务ID
  private generateTaskId(): string {
    return `upload_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // 获取上传耗时
  private getUploadDuration(task: UploadTask): number {
    if (task.startTime && task.endTime) {
      return task.endTime - task.startTime;
    }
    return 0;
  }

  // 清理已完成的任务
  cleanupCompletedTasks(): void {
    const completedTasks = this.getAllTasks().filter(task => 
      task.status === 'completed' || task.status === 'failed'
    );
    
    completedTasks.forEach(task => {
      this.tasks.delete(task.id);
    });
    
    console.log(`🧹 清理了 ${completedTasks.length} 个已完成的任务`);
  }

  // 获取统计信息
  getStats(): {
    total: number;
    pending: number;
    uploading: number;
    completed: number;
    failed: number;
  } {
    const tasks = this.getAllTasks();
    return {
      total: tasks.length,
      pending: tasks.filter(t => t.status === 'pending').length,
      uploading: tasks.filter(t => t.status === 'uploading').length,
      completed: tasks.filter(t => t.status === 'completed').length,
      failed: tasks.filter(t => t.status === 'failed').length
    };
  }
}